package com.tangcheng.redislistener.expire.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * org.springframework.data.redis.listener.KeyspaceEventMessageListener#afterPropertiesSet()
 * 会将KeyspaceEventMessageListener类型的监听自动注册到RedisMessageListenerContainer
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    /**
     * Creates new MessageListener for __keyevent@*__:expired messages.
     *
     * @param listenerContainer
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    public DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String keyName = new String(message.getBody());
        log.info("onMessage keyName {} pattern {} ", keyName, new String(pattern));
        LocalDateTime expectExpireDatetime = LocalDateTime.parse(keyName.split("@")[1], dateTimeFormatter);
        long seconds = Duration.between(expectExpireDatetime, LocalDateTime.now()).getSeconds();
        if (seconds > 1) {
            log.info("过期key {} ,滞后时间 {} seconds", keyName, seconds);
        }
    }


}